<template>
  <div class="home">
    <h1>Element ui表格组件+sortablejs实现行拖拽排序</h1>
    <div style="margin-bottom: 20px;">
      <el-button size="small" @click="addTab(editableTabsValue)">
        add tab
      </el-button>
    </div>
    <el-tabs
      v-model="editableTabsValue"
      type="card"
      closable
      @tab-remove="removeTab"
    >
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >
        {{ item.content }}
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import Sortable from "sortablejs";
export default {
  // components: {
  //   Sortable
  // },
  data() {
    return {
      editableTabsValue: "2",
      editableTabs: [
        {
          title: "Tab 1",
          name: "1",
          content: "Tab 1 content"
        },
        {
          title: "Tab 2",
          name: "2",
          content: "Tab 2 content"
        }
      ],
      tabIndex: 2
    };
  },
  mounted() {
    this.rowDrop();
  },
  methods: {
    rowDrop() {
      // 配置
      var ops = {
        onEnd({ newIndex, oldIndex }) {
          console.log(123456);
          console.log(newIndex);
          console.log(oldIndex);
          // self.list.splice(newIndex, 0, self.list.splice(oldIndex, 1)[0])
        }
      };
      const tbody = document.querySelector(
        ".el-tabs__nav-wrap .el-tabs__nav-scroll .el-tabs__nav"
      );
      Sortable.create(tbody, ops);
    },
    addTab() {
      let newTabName = ++this.tabIndex + "";
      this.editableTabs.push({
        title: "New Tab",
        name: newTabName,
        content: "New Tab content"
      });
      this.editableTabsValue = newTabName;
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }

      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    }
  }
};
</script>

<style lang="scss" scoped>
.home {
  width: 1200px;
  margin: 0 auto;
}
</style>
